package com.atom.module.document.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.atom.module.document.Document;
import com.atom.module.document.R;
import com.atom.module.document.helper.DocumentHelper;
import com.atom.module.document.utils.FileUtil;
import com.atom.module.document.view.recycler.Adapter;
import com.atom.module.logger.Logger;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;


/**
 * All rights Reserved, Designed By www.rongdasoft.com
 *
 * @version V1.0
 * @Title: DocumentListActivity
 * @Description:
 * @author: wuyongzheng
 * @date: 2022/4/2
 * @Copyright: 2022/4/2 www.rongdasoft.com Inc. All rights reserved.
 */
public class DocumentListActivity extends AbstractAppCompatActivity {

    public static class DocumentFolder {
        private final String documentPath;
        private final File sourceDocumentFile;
        private final File handleDocumentFile;
        private final List<File> sourceFiles = new ArrayList<>();
        private final List<File> handleFiles = new ArrayList<>();

        public DocumentFolder(String documentPath) {
            this.documentPath = documentPath;
            this.sourceDocumentFile = new File(documentPath, DocumentHelper.source_file);
            this.handleDocumentFile = new File(documentPath, DocumentHelper.handle_file);
            if (this.sourceDocumentFile.exists() && this.sourceDocumentFile.isDirectory()) {
                sourceFiles.addAll(Arrays.asList(Objects.requireNonNull(this.sourceDocumentFile.listFiles())));
            }
            if (this.handleDocumentFile.exists() && this.handleDocumentFile.isDirectory()) {
                handleFiles.addAll(Arrays.asList(Objects.requireNonNull(this.handleDocumentFile.listFiles())));
            }
        }

        @Override
        public String toString() {
            return "DocumentFolder{" +
                "documentPath='" + documentPath + '\'' +
                ", sourceDocumentFile=" + sourceDocumentFile +
                ", handleDocumentFile=" + handleDocumentFile +
                ", sourceFiles=" + sourceFiles +
                ", handleFiles=" + handleFiles +
                '}';
        }
    }

    public static class ViewHolder extends Adapter.ViewHolder<DocumentFolder> {

        private final TextView documentPath;
        private final TextView sourceFiles;
        private final TextView handleFiles;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            documentPath = itemView.findViewById(R.id.documentPath);
            sourceFiles = itemView.findViewById(R.id.sourceFiles);
            handleFiles = itemView.findViewById(R.id.handleFiles);
        }

        @Override
        public void onBind(DocumentFolder documentFolder) {
            documentPath.setText(documentFolder.documentPath);
            sourceFiles.setText("原始文件数目:" + documentFolder.sourceFiles.size());
            handleFiles.setText("处理文件数目:" + documentFolder.handleFiles.size());

            addOnClickListener(R.id.showSourceFiles);
            addOnClickListener(R.id.showHandleFiles);
            addOnClickListener(R.id.mergeDocumentFolder);
            addOnClickListener(R.id.addNewDocument);
        }
    }

    public static class ImageViewHolder extends Adapter.ViewHolder<File> {
        private final ImageView imageInfo;

        public ImageViewHolder(@NonNull View itemView) {
            super(itemView);
            imageInfo = itemView.findViewById(R.id.imageInfo);
        }

        @Override
        public void onBind(File file) {
            imageInfo.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_document_list);
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
        }
        initParam(savedInstanceState);
        view(R.id.documentRecyclerView, (PickView<RecyclerView>) recyclerView -> {
            recyclerView.setAdapter(new Adapter.Subject<DocumentFolder>(documentFolders, new Adapter.AbstractListener<DocumentFolder>() {
                @Override
                public void onItemClick(View view, Adapter.Subject<DocumentFolder> adapter, Adapter.ViewHolder<DocumentFolder> viewHolder, DocumentFolder documentFolder) {
                    Logger.e(documentFolder.toString());
                    if (view.getId() == R.id.itemDocumentFolder) {
                        // 进行重新处理
                        final AlertDialog.Builder builder = new AlertDialog.Builder(DocumentListActivity.this);
                        builder.setMessage("注意");
                        builder.setMessage("编辑将会把之前的处理效果恢复原装");
                        builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 将路径传如多处理界面

                            }
                        });
                        builder.setNeutralButton("cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        builder.create().show();
                    } else if (view.getId() == R.id.showSourceFiles) {
                        final AlertDialog.Builder builder = new AlertDialog.Builder(DocumentListActivity.this);
                        RecyclerView recycler = new RecyclerView(DocumentListActivity.this);
                        final Adapter.Subject<File> subject = new Adapter.Subject<File>() {

                            @Override
                            protected int getItemViewType(int position, File file) {
                                return R.layout.item_document_image;
                            }

                            @Override
                            public Adapter.ViewHolder<File> onCreateViewHolder(View contentView, int viewType) {
                                return new ImageViewHolder(contentView);
                            }
                        };
                        recycler.setAdapter(subject);

                        recycler.setLayoutManager(new LinearLayoutManager(DocumentListActivity.this));

                        builder.setView(recycler);

                        builder.setPositiveButton("source", (dialog, which) -> {
                            // TODO
                            dialog.dismiss();
                        });

                        builder.setNegativeButton("cancel", (dialog, which) -> dialog.dismiss());

                        final AlertDialog alertDialog = builder.create();

                        alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                            @Override
                            public void onShow(DialogInterface dialog) {
                                subject.addAll(documentFolder.sourceFiles);
                            }
                        });

                        alertDialog.show();
                    } else if (view.getId() == R.id.showHandleFiles) {
                        final AlertDialog.Builder builder = new AlertDialog.Builder(DocumentListActivity.this);
                        RecyclerView recycler = new RecyclerView(DocumentListActivity.this);
                        final Adapter.Subject<File> subject = new Adapter.Subject<File>() {

                            @Override
                            protected int getItemViewType(int position, File file) {
                                return R.layout.item_document_image;
                            }

                            @Override
                            public Adapter.ViewHolder<File> onCreateViewHolder(View contentView, int viewType) {
                                return new ImageViewHolder(contentView);
                            }
                        };
                        recycler.setAdapter(subject);

                        recycler.setLayoutManager(new LinearLayoutManager(DocumentListActivity.this));

                        builder.setView(recycler);

                        builder.setPositiveButton("handle", (dialog, which) -> {
                            // TODO
                            dialog.dismiss();

                        });
                        builder.setNegativeButton("cancel", (dialog, which) -> dialog.dismiss());

                        final AlertDialog alertDialog = builder.create();

                        alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                            @Override
                            public void onShow(DialogInterface dialog) {
                                subject.addAll(documentFolder.handleFiles);
                            }
                        });

                        alertDialog.show();
                    } else if (view.getId() == R.id.mergeDocumentFolder) {
                        final DocumentFolder firstDocumentFolder = adapter.getItems().get(0);
                        final DocumentFolder currDocumentFolder = documentFolder;
                        // 进行一次文件的复制开发
                        for (File sourceFile : firstDocumentFolder.sourceFiles) {
                            final boolean b = FileUtil.copyFile(sourceFile.getAbsolutePath(), currDocumentFolder.sourceDocumentFile.getAbsolutePath());
                            Logger.e(" sourceFile %s , %s", sourceFile.getAbsolutePath(), b);
                        }
                        for (File handleFile : firstDocumentFolder.handleFiles) {
                            final boolean b = FileUtil.copyFile(handleFile.getAbsolutePath(), currDocumentFolder.handleDocumentFile.getAbsolutePath());
                            Logger.e(" handleFile %s , %s", handleFile.getAbsolutePath(), b);
                        }
                        finish();
                    } else if (view.getId() == R.id.addNewDocument) {
                        // 去拍屏相机,添加路径
                        Intent intent = new Intent(DocumentListActivity.this, CameraViewActivity.class);
                        File documentFile = new File(documentFolder.documentPath);
                        intent.putExtra(DocumentHelper.document_name_param, documentFile.getName());
                        intent.putExtra(DocumentHelper.document_path_param, documentFile.getAbsolutePath());
                        startActivity(intent);
                        finish();
                    }
                }
            }) {
                @Override
                protected int getItemViewType(int position, DocumentFolder documentFolder) {
                    return R.layout.item_document_folder;
                }

                @Override
                public Adapter.ViewHolder<DocumentFolder> onCreateViewHolder(View contentView, int viewType) {
                    return new ViewHolder(contentView);
                }
            });
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
        });
    }

    private final List<DocumentFolder> documentFolders = new ArrayList<>();

    private void initParam(Bundle savedInstanceState) {
        String documentRootPath = DocumentHelper.getDocumentRootPath(this);
        File documentRootFolder = new File(documentRootPath);
        File[] files = documentRootFolder.listFiles();
        if (files == null || files.length == 0) {
            finish();
            return;
        }
        for (File file : files) {
            documentFolders.add(new DocumentFolder(file.getAbsolutePath()));
        }
        Intent intent = getIntent();
        Serializable serializableExtra = intent.getSerializableExtra(DocumentHelper.camera_result_array_param);
        if (serializableExtra instanceof ArrayList) {
            ArrayList<Document.EntryWrapper> list = (ArrayList<Document.EntryWrapper>) serializableExtra;
            Logger.e(list.toString());
        }
        Logger.e("initParam");
    }

}
